package com.djl.mvc.config;

import com.djl.crowd.entity.Admin;
import com.djl.crowd.entity.Role;
import com.djl.service.AdminService;
import com.djl.service.AuthService;
import com.djl.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author le
 * @Date 2022/2/8 12:52
 * @Version 1.0
 */
@Component
public class CrowdUserDetailsService implements UserDetailsService {

    @Autowired
    private AdminService adminService;

    @Autowired
    private RoleService roleService;

    @Autowired
    private AuthService authService;


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        Admin admin = adminService.getAdminByLoginAcct(username);

        if (admin == null) {
            return null;
        }

        Integer adminId = admin.getId();
        List<Role> assignedRoles = roleService.getAssignedRole(adminId);
        List<String> assignedAuthNames = authService.getAssignedAuthNameByAdminId(adminId);

        // 创建集合对象用来存储GrantedAuthority
        List<GrantedAuthority> authorities = new ArrayList<>();
        for (Role assignedRole : assignedRoles) {
            String roleName = "ROLE_" + assignedRole.getName();
            SimpleGrantedAuthority simpleGrantedAuthority = new SimpleGrantedAuthority(roleName);
            authorities.add(simpleGrantedAuthority);
        }

        SecurityAdmin securityAdmin = new SecurityAdmin(admin,authorities);
        return securityAdmin;
    }
}
